<script setup lang="ts">
import { requiredCheck } from "@/utils/verify";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { editData, getDataByPage } from "@/api/modules/system/account";
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);
const router = useRouter();

interface Props {
  title?: string;
  rowData?: Object;
  isSelf?: Boolean; // 是否修改当前登录账号
}

const props = withDefaults(defineProps<Props>(), {
  title: "重置密码",
  rowData: undefined,
  isSelf: false
});
defineOptions({
  name: "UpdateFormPassword" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ElMessage } from "element-plus";
import { LOGIN_URL } from "@/config";
import { cfgPamGet } from "@/api/modules/system/params";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle ,rowId} = useUpdate({
  rules: {
    userName: [...requiredCheck("请输入用户名称")],
    roleIds: [...requiredCheck("请选择角色")],
    password: [
      ...requiredCheck("请输入密码"),
      {
        validator: (rule, value, callback) => {
          const checkPasswordRules = passwordPwd.value;
          const getTip = () => {
            let str = "密码长度至少" + Number(checkPasswordRules.min_length) + "位";
            let isLetterAndNumber = false;
            let isLetterSpecialChar = false;
            if (Number(checkPasswordRules.char_number)) {
              isLetterAndNumber = true;
              str += `且包含字母和数字`;
            }
            if (Number(checkPasswordRules.upper_lower)) {
              isLetterSpecialChar = true;
              if (isLetterAndNumber) {
                str += `、大小写混合`;
              } else {
                str += `且包含大小写混合`;
              }
            }
            if (Number(checkPasswordRules.special_char)) {
              if (isLetterSpecialChar || isLetterAndNumber) {
                str += `和特殊字符`;
              } else {
                str += `且包含特殊字符`;
              }
            }
            return str;
          };
          const tipMsg = getTip();
          // 密码需要字母和数字
          const letterAndNumber = /^(?=.*[a-zA-Z])(?=.*\d).+$/;
          // 包含特殊字符
          const specialCharacter = /[!@#$%^&*\/(),.?":{}|<>]/;
          // 大小写混合
          const mixedCase = /^(?=.*[a-z])(?=.*[A-Z]).+$/;
          // 判断密码最小长度
          if (value.length < Number(checkPasswordRules.min_length)) {
            callback(new Error(tipMsg));
          }
          // 是否字母加数字
          if (Number(checkPasswordRules.char_number)) {
            // showPasswordDialog
            if (!letterAndNumber.test(value)) {
              callback(new Error(tipMsg));
            }
          }
          // 是否特殊字符
          if (Number(checkPasswordRules.special_char)) {
            if (!specialCharacter.test(value)) {
              callback(new Error(tipMsg));
            }
          }
          // 是否大小写混合
          if (Number(checkPasswordRules.upper_lower)) {
            if (!mixedCase.test(value)) {
              callback(new Error(tipMsg));
            }
          }
          callback();
        }
      }
    ],
    passwordRe: [
      {
        validator: (rule, value, callback) => {
          if (value !== updateFormData.password) {
            callback(new Error("两次输入的密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  },
  defaultData: {}
});
// onMounted(() => {
//   console.info(props.rowData);
// });
//
const userInfoNames = computed(() => userStore.userInfo.name);

async function submitCb() {
  const name = updateFormData.name;

  if (props.isSelf) {
    const roleMap = new Map([
      ["系统管理员", "1"],
      ["安全管理员", "2"],
      ["审计管理员", "3"]
    ]);
    const res = await getDataByPage({
      pageNum: 0,
      pageSize: 100
    });
    console.log("res", res);
    console.log("userInfoNames", userInfoNames);
    let list = res.result.data;
    const userinfo = list.find(item => item[1] === userInfoNames.value);
    updateFormData.id =userinfo[userinfo.length - 1]
    updateFormData.name = userinfo[1];
    updateFormData.role = roleMap.get(userinfo[2]);
    rowId.value = updateFormData.id;
  }
    console.log(updateFormData);
  await submit({
    addData: editData,
    updateApi: editData,
    sendData: {
      name: updateFormData.name,
      passwordRe: updateFormData.passwordRe || "",
      password: updateFormData.password || "",
      role: updateFormData.role,
      id: updateFormData?.id
    }
  });
  console.log(username.value);
  console.log(name);
  if (username.value === name||props.isSelf) {
    setTimeout(() => {
      ElMessage.success("您的密码已重置，请重新登录!");
    }, 1500);
    setTimeout(() => {
      // 2.清除 Token
      userStore.setToken("");
      localStorage.clear();
      sessionStorage.clear();
      // 3.重定向到登陆页
      router.replace(LOGIN_URL);
    }, 2500);
  }
  emits("success");
}

const passwordPwd = ref({});

async function getCfg() {
  const res = await cfgPamGet();
  console.log("res", res);
  passwordPwd.value = res;
}
</script>

<template>
  <div
    class="update-form mg-r-sm"
    style="display: inline-block"
    @click="
      openHandle({
        row: {
          ...rowData,
          status: 1,
          id: props.rowData?.id
        },
        id: props.rowData?.id
      });
      getCfg();
    "
  >
    <slot>
      <el-button type="primary">新增</el-button>
    </slot>
  </div>
  <base-dialog @confirm="submitCb()" width="450px" :title="title" v-model="showHandle">
    <div class="details">
      <div class="details-main">
        <el-form ref="updateFormRef" :model="updateFormData" :rules="updateFormRules" label-width="120px" label-suffix="：">
          <el-form-item v-if="!isSelf" label="用户名" prop="name">
            <el-input style="width: 240px" disabled v-model="updateFormData.name" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item :label="isSelf ? '新密码' : '用户密码'" prop="password">
            <el-input
              style="width: 240px"
              show-password
              v-model.trim="updateFormData.password"
              autocomplete="off"
              placeholder="请输入密码"
              maxlength="20"
              aria-autocomplete="none"

              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item :label="isSelf ? '确认密码' : '确认密码'" prop="passwordRe">
            <el-input
              show-password
              style="width: 240px"
              type="password"
              placeholder="请再次输入密码"
              v-model.trim="updateFormData.passwordRe"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer-more-button></template>
  </base-dialog>
</template>

<style lang="scss" scoped></style>
